package com.example.mybusschedule.ui

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mybusschedule.data.BusSchedule
import com.example.mybusschedule.data.BusScheduleRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.TimeZone
import javax.inject.Inject

@HiltViewModel
class BusScheduleViewModel @Inject constructor(private val busScheduleRepository: BusScheduleRepository) : ViewModel() {
    var state by mutableStateOf(BusScheduleUiState())
        private set

    init {
        viewModelScope.launch {
            busScheduleRepository.getAllBusSchedules().collect {
                state = state.copy(
                    busSchedules = it
                )
            }
        }
    }

    fun resetHomeScreenStates() {
        state = state.copy(isShowingHomepage = true)
    }

    suspend fun updateCurrentStop(stopName: String) {
        busScheduleRepository.getBusScheduleByStopName(stopName).collect {
            state = state.copy(
                currentBusStopSchedules = it,
                isShowingHomepage = false
            )
        }
    }
}

fun BusSchedule.time(): String {
    val instant = Instant.ofEpochSecond(this.arrivalTimeInMillis.toLong())
    val dateTime = instant.atZone(TimeZone.getDefault().toZoneId())
    return dateTime.format(DateTimeFormatter.ofPattern("hh:mm a"))
}

data class BusScheduleUiState(
    val busSchedules: List<BusSchedule> = emptyList(),
    val currentBusStopSchedules: List<BusSchedule> = emptyList(),
    val isShowingHomepage: Boolean = true
)
